package hu.dobrosi.dinkycam.j2me.util;

import hu.dobrosi.dinkycam.j2me.forms.DinkycamForm;
import hu.dobrosi.util.StringUtil;

import java.util.Enumeration;
import java.util.Hashtable;

import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Item;
import javax.microedition.lcdui.TextField;
import javax.microedition.rms.RecordEnumeration;
import javax.microedition.rms.RecordStore;
import javax.microedition.rms.RecordStoreException;

public class Preferences {
	private String mRecordStoreName;

	private Hashtable mHashtable;

	public Preferences(String recordStoreName) throws RecordStoreException {
		mRecordStoreName = recordStoreName;
		mHashtable = new Hashtable();
		load();
	}

	private String getItemId(DinkycamForm form, Item item) {
		return form.getId() + "#" + item.getLabel();
	}

	public void loadTextFieldValue(DinkycamForm form, TextField tf) {
		Object v = get(getItemId(form, tf));
		if (v != null) {
			tf.setString(v.toString());
		}
	}

	public void saveTextFieldValue(DinkycamForm form, TextField tf) {
		put(getItemId(form, tf), tf.getString());
	}

	public void loadChoiceGroupValue(DinkycamForm form, ChoiceGroup cg) {
		Object v = get(getItemId(form, cg));
		if (v != null) {
			Object[] va = StringUtil.splitString(v.toString(), ",");
			boolean[] bv = new boolean[va.length];
			for (int i = 0; i < bv.length; i++) {
				bv[i] = va[i].toString().equalsIgnoreCase("TRUE");
			}
			if (bv.length == cg.size()) {
				cg.setSelectedFlags((boolean[]) bv);
			}
		}
	}

	public void saveChoiceGroupValue(DinkycamForm form, ChoiceGroup cg) {
		boolean[] selectedArray = new boolean[cg.size()];
		cg.getSelectedFlags(selectedArray);
		put(getItemId(form, cg), selectedArray);
	}

	public Object get(DinkycamForm form, TextField tf) {
		return get(getItemId(form, tf));
	}	
	
	public Object get(String key) {
		Object res = mHashtable.get(key);
		return res;
	}

	public void put(String key, Object value) {
		if (value == null)
			value = "";
		mHashtable.put(key, value);
	}

	private void load() throws RecordStoreException {
		RecordStore rs = null;
		RecordEnumeration re = null;

		try {
			rs = RecordStore.openRecordStore(mRecordStoreName, true);
			re = rs.enumerateRecords(null, null, false);
			while (re.hasNextElement()) {
				byte[] raw = re.nextRecord();
				String pref = new String(raw);
				// Parse out the name.
				int index = pref.indexOf('|');
				String name = pref.substring(0, index);
				String value = pref.substring(index + 1);
				put(name, value);
			}
		} finally {
			if (re != null)
				re.destroy();
			if (rs != null)
				rs.closeRecordStore();
		}
	}

	public void save() throws RecordStoreException {
		RecordStore rs = null;
		RecordEnumeration re = null;
		try {
			rs = RecordStore.openRecordStore(mRecordStoreName, true);
			re = rs.enumerateRecords(null, null, false);

			// First remove all records, a little clumsy.
			while (re.hasNextElement()) {
				int id = re.nextRecordId();
				rs.deleteRecord(id);
			}

			// Now save the preferences records.
			Enumeration keys = mHashtable.keys();
			while (keys.hasMoreElements()) {
				String key = (String) keys.nextElement();
				Object value = get(key);
				if (value instanceof boolean[]) {
					String nvalue = "";
					for (int i = 0; i < ((boolean[]) value).length; i++) {
						if (i != 0) {
							nvalue += ",";
						}
						nvalue += ((boolean[]) value)[i];
					}
					value = nvalue;
				}

				String pref = key + "|" + value;
				byte[] raw = pref.getBytes();
				rs.addRecord(raw, 0, raw.length);
			}
		} finally {
			if (re != null)
				re.destroy();
			if (rs != null)
				rs.closeRecordStore();
		}
	}
}